<template>
  <view class="chat-container">
    <view class="status-bar" :style="{height: statusBarHeight + 'px'}"></view>
    
    <!-- 顶部区域 -->
    <view class="chat-header" v-if="messages.length === 0">
      <view class="bot-avatar-wrapper">
        <image class="bot-avatar" src="https://img1.baidu.com/it/u=2620468253,355479354&fm=253&app=120&f=JPEG?w=800&h=800" mode="aspectFill"></image>
      </view>
      <text class="title">您想问什么呢？</text>
      <text class="subtitle">无论大小，任何问题都可以。</text>
    </view>

    <!-- 内容区域 -->
    <scroll-view 
      scroll-y 
      class="content-area" 
      :scroll-top="scrollTop" 
      :scroll-with-animation="true"
      :enable-flex="true"
    >
      <view class="content-wrapper">
        <!-- 预设问题 -->
        <view v-if="messages.length === 0" class="preset-list">
          <view 
            class="preset-item" 
            v-for="(item, index) in presetQuestions" 
            :key="index"
            @click="sendPreset(item)"
          >
            <text>{{ item }}</text>
          </view>
        </view>

        <!-- 消息列表 -->
        <view v-else class="message-list">
          <view v-for="(msg, index) in messages" :key="index" class="message-row" :class="msg.role">
            
            <!-- AI 头像 -->
            <view v-if="msg.role === 'assistant'" class="msg-avatar ai-avatar">
              <image src="https://img1.baidu.com/it/u=2620468253,355479354&fm=253&app=120&f=JPEG?w=800&h=800" mode="aspectFill"></image>
            </view>

            <!-- 消息内容容器 -->
            <view class="msg-content-container">
              <!-- 消息气泡 -->
              <view class="msg-bubble">
                <text class="msg-text">{{ msg.content }}</text>
              </view>

              <!-- 塔罗概览模块 (仅在用户第一条消息且有塔罗数据时显示) -->
              <view v-if="msg.showOverview && tarotResult.length > 0" class="tarot-overview">
                <view class="overview-title">塔罗概览</view>
                <view class="cards-container">
                  <view v-for="(card, cIndex) in tarotResult" :key="cIndex" class="card-item">
                    <image :src="card.image_url" mode="aspectFit" class="card-img"></image>
                    <text class="card-name">{{ card.name_cn }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          
          <!-- Loading 状态 -->
          <view v-if="isLoading" class="message-row assistant">
            <view class="msg-avatar ai-avatar">
              <image src="https://img1.baidu.com/it/u=2620468253,355479354&fm=253&app=120&f=JPEG?w=800&h=800" mode="aspectFill"></image>
            </view>
            <view class="msg-bubble loading-bubble">
              <view class="dot-flashing"></view>
            </view>
          </view>
        </view>
        
        <!-- 占位，防止底部遮挡 -->
        <view style="height: 140rpx;"></view>
      </view>
    </scroll-view>

    <!-- 底部输入区 -->
    <view class="input-area safe-area-bottom">
      <view class="input-wrapper">
        <input 
          class="input-field" 
          v-model="inputText" 
          placeholder="写出您的问题" 
          placeholder-class="input-placeholder"
          confirm-type="send"
          @confirm="sendMessage"
        />
        <view class="send-btn" @click="sendMessage">
          <text class="arrow-icon">↑</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { buildApiUrl, TAROT_API } from '@/config/api.js';

export default {
  data() {
    return {
      statusBarHeight: 20,
      inputText: '',
      messages: [],
      presetQuestions: [
        '未来三个月复合的可能性有多大？',
        '我应该主动联系TA吗，TA的反应会是积极还是消极？',
        '这段关系是否值得我继续争取，还是更适合放手？',
        '对方会对这段关系采取什么样的行动？'
      ],
      scrollTop: 0,
      isLoading: false,
      tarotResult: [] // 接收上个页面传来的塔罗牌数据
    };
  },
  onLoad(options) {
    const sysInfo = uni.getSystemInfoSync();
    this.statusBarHeight = sysInfo.statusBarHeight || 20;
    
    // 接收参数
    if (options.cards) {
      try {
        this.tarotResult = JSON.parse(decodeURIComponent(options.cards));
        console.log('收到的塔罗牌数据:', this.tarotResult);
      } catch (e) {
        console.error('解析塔罗牌数据失败', e);
      }
    }
  },
  methods: {
    sendPreset(text) {
      this.inputText = text;
      this.sendMessage();
    },
    sendMessage() {
      if (!this.inputText.trim()) return;

      const question = this.inputText;
      this.inputText = '';

      // 添加用户消息
      const isFirstMessage = this.messages.length === 0;
      this.messages.push({
        role: 'user',
        content: question,
        showOverview: isFirstMessage
      });
      
      this.scrollToBottom();
      this.isLoading = true;

      // 调用 AI 接口
      this.callAiApi(question);
    },
    callAiApi(question) {
      // 构造 history 参数 (排除当前正在发送的这条消息)
      const history = this.messages.slice(0, -1).map(msg => ({
        role: msg.role,
        content: msg.content
      }));

      // 构造 cards 参数
      const cards = this.tarotResult.map(card => ({
        id: card.id,
        is_up: card.is_up === 2 ? '2' : '1' // 1=正位, 2=逆位
      }));

      uni.request({
        url: buildApiUrl(TAROT_API.chat),
        method: 'POST',
        data: {
          question: question,
          history: history,
          cards: cards
        },
        success: (res) => {
          if (res.data.code === 1) {
            this.messages.push({
              role: 'assistant',
              content: res.data.data
            });
          } else {
            uni.showToast({
              title: res.data.msg || '请求失败',
              icon: 'none'
            });
            // 添加一条错误提示消息，或者不添加，视交互需求而定
            // 这里选择添加一条友好的错误提示
            this.messages.push({
              role: 'assistant',
              content: '抱歉，我连接宇宙信号时遇到了一点干扰，请稍后再试。'
            });
          }
        },
        fail: (err) => {
          console.error('API Request Failed:', err);
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
          this.messages.push({
            role: 'assistant',
            content: '网络连接似乎有点问题，请检查您的网络设置。'
          });
        },
        complete: () => {
          this.isLoading = false;
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        }
      });
    },
    scrollToBottom() {
      setTimeout(() => {
        this.scrollTop = 99999;
      }, 100);
    }
  }
};
</script>

<style scoped>
.chat-container {
  width: 100%;
  height: 100vh;
  background-color: #233040;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止整体滚动 */
}

.content-area {
  flex: 1;
  width: 100%;
  overflow: hidden;
  min-height: 0; /* 确保flex子项正确收缩 */
}

.content-wrapper {
  padding: 30rpx;
  /* min-height: 100%; 移除此行，避免强制撑满导致可能的微小滚动或误解 */
  box-sizing: border-box;
}

/* 顶部样式 */
.chat-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 60rpx;
  margin-bottom: 60rpx;
  animation: fade-in 0.8s ease-out;
}

.bot-avatar-wrapper {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 30rpx;
}

.bot-avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  color: #4A90E2; /* 亮蓝色标题 */
  margin-bottom: 16rpx;
}

.subtitle {
  font-size: 28rpx;
  color: #8FA0B3;
}

/* 预设问题列表 */
.preset-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  animation: slide-up 0.5s ease-out;
}

.preset-item {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 20rpx;
  padding: 30rpx;
  color: #E0E0E0;
  font-size: 30rpx;
  transition: all 0.2s;
}

.preset-item:active {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(0.99);
}

/* 消息列表样式 */
.message-row {
  display: flex;
  margin-bottom: 40rpx;
  align-items: flex-start;
}

/* 机器人消息：默认左对齐 */
.message-row.assistant {
  justify-content: flex-start;
}

/* 用户消息：右对齐 */
.message-row.user {
  justify-content: flex-end;
}

.msg-content-container {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message-row.user .msg-content-container {
  align-items: flex-end;
}

.message-row.assistant .msg-content-container {
  align-items: flex-start;
  max-width: 100%; /* 机器人消息容器宽度由内部气泡决定，但受外层限制 */
}

.msg-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  margin-right: 20rpx; /* AI 头像右侧间距 */
}

.ai-avatar image {
  width: 100%;
  height: 100%;
}

.msg-bubble {
  width: fit-content; /* 适应内容宽度 */
  max-width: 100%; /* 相对于 msg-content-container */
  padding: 24rpx 30rpx;
  border-radius: 24rpx;
  font-size: 30rpx;
  line-height: 1.5;
  position: relative;
  word-break: break-all;
}

.assistant .msg-bubble {
  background: rgba(255, 255, 255, 0.1);
  color: #E0E0E0;
  border-top-left-radius: 4rpx;
}

.user .msg-bubble {
  background: #4A90E2;
  color: #FFFFFF;
  border-top-right-radius: 4rpx;
  margin-right: 0;
}

/* 底部输入区 */
.input-area {
  width: 100%;
  background: #233040;
  padding: 20rpx 30rpx;
  /* 适配全面屏底部安全区域 */
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  box-sizing: border-box; /* 关键：防止padding撑大宽度导致偏右 */
  flex-shrink: 0; /* 防止被内容挤压 */
  position: relative; /* 改为相对定位，依靠flex布局置底 */
}

.input-wrapper {
  display: flex;
  align-items: center;
  background: #1A2430;
  border-radius: 40rpx;
  padding: 10rpx 10rpx 10rpx 30rpx;
  border: 1px solid rgba(255, 255, 255, 0.2);
  width: 100%; /* 确保填满容器 */
  box-sizing: border-box;
}

.input-field {
  flex: 1;
  height: 80rpx;
  font-size: 30rpx;
  color: #FFFFFF;
}

.input-placeholder {
  color: #6E7C8C;
}

.send-btn {
  width: 70rpx;
  height: 70rpx;
  background: #4A90E2;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 20rpx;
}

.arrow-icon {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  transform: translateY(-2rpx);
}

/* 动画 */
@keyframes fade-in {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slide-up {
  from { transform: translateY(20px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

/* Loading 动画点 */
.loading-bubble {
  display: flex;
  align-items: center;
  height: 40rpx;
  padding: 20rpx 30rpx;
}

.dot-flashing {
  position: relative;
  width: 10rpx;
  height: 10rpx;
  border-radius: 5px;
  background-color: #E0E0E0;
  color: #E0E0E0;
  animation: dot-flashing 1s infinite linear alternate;
  animation-delay: 0.5s;
}

.dot-flashing::before, .dot-flashing::after {
  content: '';
  display: inline-block;
  position: absolute;
  top: 0;
}

.dot-flashing::before {
  left: -15rpx;
  width: 10rpx;
  height: 10rpx;
  border-radius: 5px;
  background-color: #E0E0E0;
  color: #E0E0E0;
  animation: dot-flashing 1s infinite alternate;
  animation-delay: 0s;
}

.dot-flashing::after {
  left: 15rpx;
  width: 10rpx;
  height: 10rpx;
  border-radius: 5px;
  background-color: #E0E0E0;
  color: #E0E0E0;
  animation: dot-flashing 1s infinite alternate;
  animation-delay: 1s;
}

@keyframes dot-flashing {
  0% { background-color: #E0E0E0; }
  50%, 100% { background-color: rgba(224, 224, 224, 0.2); }
}

/* 塔罗概览样式 */
.tarot-overview {
  margin-top: 20rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16rpx;
  padding: 20rpx;
  width: 100%;
  box-sizing: border-box;
  border: 1px solid rgba(255, 255, 255, 0.15);
}

.overview-title {
  font-size: 24rpx;
  color: #8FA0B3;
  margin-bottom: 16rpx;
}

.cards-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.card-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 120rpx;
}

.card-img {
  width: 120rpx;
  height: 200rpx;
  border-radius: 8rpx;
  margin-bottom: 8rpx;
  background-color: rgba(0,0,0,0.2);
}

.card-name {
  font-size: 22rpx;
  color: #E0E0E0;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}
</style>
